import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Queue;

/**
 * Created with IntelliJ IEDA.
 * Description:
 * User:86186
 * Date:2023-05-07
 * Time:22:04
 */

/**
 * BM27 按之字形顺序打印二叉树
 */

public class Print {
    public ArrayList<ArrayList<Integer>> Print(TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> lists = new ArrayList<>();
        if (pRoot == null){
            return lists;
        }
        Queue<TreeNode> queue = new ArrayDeque<>();
        queue.add(pRoot);
        int count = 1;
        while (!queue.isEmpty()){
            int size = queue.size();
            ArrayList<Integer> list = new ArrayList<>();
            for (int i = 0; i < size; i++) {
                TreeNode tmp = queue.poll();
                list.add(tmp.val);
                if (tmp.left != null){
                    queue.add(tmp.left);
                }
                if (tmp.right != null){
                    queue.add(tmp.right);
                }
            }
            if (count % 2 == 0){
                Collections.reverse(list);
            }
            lists.add(list);
            count++;
        }
        return lists;
    }
}
